package com.changgou.order.service.impl;

import com.changgou.entity.IdWorker;
import com.changgou.entity.Result;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.feign.SpuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.goods.pojo.Spu;
import com.changgou.order.pojo.OrderItem;
import com.changgou.order.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by zhangyuhong
 * Date:2020/5/18
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SkuFeign skuFeign;
    @Autowired
    private SpuFeign spuFeign;
    @Autowired
    private IdWorker idWorker;


    /**
     * @param num  商品数量
     * @param id  商品的sku id
     * @param username  用户名
     */
    @Override
    public void add(Integer num, Long id, String username) {
        if(num<=0){
            //说明你不想买了 就删除掉
            redisTemplate.boundHashOps("Cart_"+username).delete(id);
            return;
        }


        //对照tb_order_item表增加数据
        //1.调用feign获取tb_sku里的信息 通过id
       Result<Sku> skuResult =skuFeign.findById(id);
        //2.增加到数据库表里tb_order_item
        Sku sku = skuResult.getData();
        OrderItem orderItem = new OrderItem();
        orderItem.setId(idWorker.nextId()+"");
        //categoryid1 2 3  根据spuid通过调用feign 获取spu的对象 再获取1 2 3 分类的ID
        Result<Spu> spuResult = spuFeign.findById(sku.getSpuId());
        Spu spu = spuResult.getData();
        orderItem.setCategoryId1(spu.getCategory1Id());
        orderItem.setCategoryId2(spu.getCategory2Id());
        orderItem.setCategoryId3(spu.getCategory3Id());

        orderItem.setSkuId(sku.getId());
        orderItem.setSpuId(sku.getSpuId());
        orderItem.setName(sku.getName());
        orderItem.setPrice(sku.getPrice());  //价格
        orderItem.setNum(num);//数量
        orderItem.setMoney(sku.getPrice()*num);//金额 money
        orderItem.setPayMoney(sku.getPrice()*num); //实付金额 pay_money,这里暂时不做优惠处理
        //3.添加orderItem 添加到redis(购物车)中
redisTemplate.boundHashOps("Cart_"+username).put(id,orderItem);  //hash(相当于map  id为key,orderItem为value
// )的原因是:不能重复
    }

    /***
     * 查询用户购物车数据
     * @param username
     * @return
     */
    @Override
    public List<OrderItem> list(String username) {

        //查询所有购物车数据  缓存中读取.因为add的时候就就增加到缓存中了
        List<OrderItem> orderItems = redisTemplate.boundHashOps("Cart_"+username).values();
        return orderItems;
    }


}
